/*
 * ImageRestlet.java
 * 
 * Created on 2007-10-18, 00:02:16
 * 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package info.mikrotubula.server;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.restlet.Restlet;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.apache.log4j.Logger;
/**
 *
 * @author Krystian
 */
public class ImageUpload extends Restlet {
    
    static Logger logger = Logger.getLogger(ImageUpload.class);
    
    @Override
    public void handle(Request request, Response response) {
        logger.info("Starting upload");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1000240);
        RestletFileUpload upload = new RestletFileUpload(factory);
        List<FileItem> items;
        try {
            logger.info("Parsing request");
            items = upload.parseRequest(request);
            logger.info("Processing files");
            for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem fi = it.next();
                logger.info("Processing files: " + fi.getName());
                if (fi.getFieldName().equals("fileToUpload")) {
                    File file = new File("d:\\"+fi.getName());
                    fi.write(file);
                }      
            }
            logger.info("Processing finished");
        } catch (FileUploadException e) {
            logger.error("Something wrong with files" + e.getMessage());
            logger.error(e);
        } catch (Exception e) {
            logger.error("Something wrong " + e.getMessage());
            logger.error(e);
        }
    }

}
